# -*- encoding: utf-8 -*-
"""
-文件：proof_of_work.py
-说明：工作量证明
-作者：tlj
寻找hash后前导0满足要求的block.nonce的值
"""
from .block import Block
import sys


class ProofOfWork:
    MAX_NONCE = sys.maxsize

    def __init__(self, difficulty_bits=12):
        """
        :param difficulty_bits: 默认12位前导0
        """
        # 满足要求的block.nonce的值必小于self._target
        self._target = 1 << (256-difficulty_bits)

    def mine_block(self, data, prev_hash, height):
        """挖矿"""
        tmp_block = Block(data, prev_hash, height)
        while tmp_block.nonce < ProofOfWork.MAX_NONCE:
            hash_init = int(tmp_block.hash_(), 16)
            if hash_init < self._target:
                break   # 如果hash值小于target则满足前导0要求
            else:
                tmp_block.nonce += 1  # 通过调整nonce值满足要求

        return tmp_block

    def validate_block(self, block):
        """
        验证hash值是否满足要求
        :param block:
        :return:
        """
        hash_int = int(block.hash_(), 16)
        return True if hash_int < self._target else False

